﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using WpfWordsLearner.Model;

namespace WpfWordsLearner
{
	public class WordsManager
	{
		private static readonly WordsManager m_manager;
		private XDocument m_doc = null;
		private string m_pathToDoc;
		
		static WordsManager()
		{
			m_manager = new WordsManager();
		}

		private WordsManager()
		{
		}

		public static WordsManager Instance
		{
			get
			{
				return m_manager;
			}
		}

		public bool AddWord(string english, string translate)
		{
			if (string.IsNullOrEmpty(english) || string.IsNullOrEmpty(translate))
				return false;
			try
			{
				m_doc.Root.Add(new XElement("Word",
										new XElement("English", english),
										new XElement("Translate", translate)));
				this.SaveAndReload();
				return true;
			}
			catch { }
			return false;
		}

		public bool AddWordRange(List<Model.WordsModel> words)
		{
			if (words == null || words.Count == 0)
				return false;
			try
			{
				foreach (Model.WordsModel word in words)
				{
					m_doc.Root.Add(new XElement("Word",
											new XElement("English", word.EnglishWord),
											new XElement("Translate", word.Translate)));
				}
				this.SaveAndReload();
				return true;
			}
			catch { }
			return false;
		}

		public string GetTranslateWord(string english)
		{
			try
			{
				string data = (from item in m_doc.Root.Elements("Word")
							   where item.Element("English").Value.Contains(english)
							   select item.Element("Translate").Value).FirstOrDefault();
				return data;
			}
			catch { }
			return string.Empty;
		}

		public string GetEnglishWord(string translate)
		{
			try
			{
				string data = (from item in m_doc.Root.Elements("Word")
							   where item.Element("Translate").Value.Contains(translate)
							   select item.Element("English").Value).FirstOrDefault();
				return data;
			}
			catch { }
			return string.Empty;
		}

		public List<WordsModel> GetWordsList()
		{
			try
			{
				List<WordsModel> words = null;
				words = (from item in m_doc.Root.Elements("Word")
						 select new WordsModel()
						 {
							 EnglishWord = item.Element("English").Value,
							 Translate = item.Element("Translate").Value
						 }).ToList();
				return words;
			}
			catch { }
			return null;
		}

		private void SaveAndReload()
		{
			if (!string.IsNullOrEmpty(m_pathToDoc))
			{
				m_doc.Save(m_pathToDoc);
				m_doc = XDocument.Load(m_pathToDoc);
			}
		}

		public void SetPreference(string xmlDoc)
		{
			if (string.IsNullOrEmpty(xmlDoc) || !System.IO.File.Exists(xmlDoc))
				throw new ArgumentNullException("XmlDoc");
			m_doc = XDocument.Load(xmlDoc);
			m_pathToDoc = xmlDoc;
		}

		public void SaveChanges()
		{
			SaveAndReload();
		}
	}
}
